﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;

namespace Blog
{
    /// <summary>
    /// Summary description for Blogservice
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Blogservice : System.Web.Services.WebService, Blogpostdelivery
    {
        [WebMethod]
        public bool AddEntry(string username, string language, string title, string body)
        {
            try
            {
                lock (this.GetType())
                {
                    //<post title="Velkommen til bloggen" author="Jasper Theisen" language="DK" date="25-04-1972" postid="2">
                    XDocument doc = XDocument.Load(Server.MapPath("~/App_Data/Blog.xml"));
                    XElement elem = new XElement("post", new XCData(body));
                    elem.SetAttributeValue("title", title);
                    elem.SetAttributeValue("author", username);
                    elem.SetAttributeValue("language", language);
                    elem.SetAttributeValue("date", DateTime.UtcNow.ToString("s"));

                    int nextId = GetNextAvailableId(doc);

                    elem.SetAttributeValue("postid", Convert.ToString(nextId));
                    doc.Root.Element("posts").Add(elem);
                    doc.Save(Server.MapPath("~/App_Data/Blog.xml"));
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

        public string GetUsernames()
        {
            throw new NotImplementedException();
        }

        public string GetEntriesByUser(string username, int count, int offset)
        {
            throw new NotImplementedException();
        }

        public string GetEntries(int count, int offset)
        {
            throw new NotImplementedException();
        }

        private int GetNextAvailableId(XDocument doc)
        {
            try
            {
                int id = Convert.ToInt32((from c in doc.Descendants("post")
                                          orderby Convert.ToInt32(c.Attribute("postid").Value) descending
                                          select c.Attribute("postid").Value).First());
                return id + 1;
            }
            catch
            {
                return 1;
            }
        }
    }
}
